package org.codeblue.support.json;

import com.alibaba.fastjson.serializer.*;

/**
 * see http://blog.csdn.net/moneyshi/article/details/51830329
 * QuoteFieldNames———-输出key时是否使用双引号,默认为true
 * WriteMapNullValue——–是否输出值为null的字段,默认为false
 * WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
 * WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
 * WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
 * WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null
 */
public class FastJson {

    /**
     * @param source
     * @return
     */
    public static String toJson(Object source, SerializeFilter... serializeFilters) {
        try {
            SerializeWriter out = new SerializeWriter();

            JSONSerializer serializer = new JSONSerializer(out);
            serializer.config(SerializerFeature.DisableCircularReferenceDetect, true);
            serializer.config(SerializerFeature.DisableCheckSpecialChar, false);
            serializer.config(SerializerFeature.WriteMapNullValue, true);
            serializer.config(SerializerFeature.SortField, false);
            serializer.config(SerializerFeature.WriteNullNumberAsZero, true);
            serializer.config(SerializerFeature.WriteNullListAsEmpty, true);
            serializer.config(SerializerFeature.WriteNullStringAsEmpty, true);
            serializer.config(SerializerFeature.WriteNullBooleanAsFalse, true);
//            serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
//
//            serializer.setDateFormat("yyyy-MM-dd HH:mm:ss");
            for (SerializeFilter filter : serializeFilters) {
                if (filter != null) {
                    if (filter instanceof PropertyPreFilter) {
                        serializer.getPropertyPreFilters().add((PropertyPreFilter) filter);
                    }

                    if (filter instanceof NameFilter) {
                        serializer.getNameFilters().add((NameFilter) filter);
                    }

                    if (filter instanceof ValueFilter) {
                        serializer.getValueFilters().add((ValueFilter) filter);
                    }

                    if (filter instanceof PropertyFilter) {
                        serializer.getPropertyFilters().add((PropertyFilter) filter);
                    }

                    if (filter instanceof BeforeFilter) {
                        serializer.getBeforeFilters().add((BeforeFilter) filter);
                    }

                    if (filter instanceof AfterFilter) {
                        serializer.getAfterFilters().add((AfterFilter) filter);
                    }
                }
            }
            serializer.write(source);
            return out.toString();
        } catch (Throwable e) {
            throw new RuntimeException("JsonUtil.toJson error source=" + source, e);
        }
    }
}